export let BASE_URL = ""
// 获取当前帐号信息
const accountInfo = wx.getAccountInfoSync()
// env类型
let env = accountInfo.miniProgram.envVersion

if (!accountInfo && !env) {
  console.error("获取运行环境失败!")
} else {
  console.log("当前运行环境：" + env)
  const envURL = {
    // 开发版
    develop: "http://localhost:8080",
    // 体验版
    trial: "http://localhost:8080",
    // 正式版
    release: "http://localhost:8080"
  }
  BASE_URL = envURL[env]
}

export default class Request {

  static request(url: string, data: any, method: "POST" | "GET" | "PUT" | "DELETE") {
    const token = wx.getStorageSync("token")
    return new Promise((resolve, reject) => {
      wx.request({
        url: BASE_URL + url,
        data: data,
        method: method,
        header: { Authorization: token },
        success(res: any) {
          let code = res.data.code
          if (code === "SUCCESS") {
            resolve(res.data)
          }
          if (code === "NOT_LOGIN") {
            wx.removeStorageSync("user")
            wx.removeStorageSync("token")
            wx.reLaunch({
              url: "/pages/login/login"
            })
          }
          reject(res.data.message)
        },
        fail(e) {
          reject(e.errMsg)
        }
      })
    })
  }

  static upload(url: string, path: string, name: string = "file") {
    const token = wx.getStorageSync("token")
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: BASE_URL + url,
        filePath: path,
        name,
        header: { Authorization: token },
        success(res) {
          let result = JSON.parse(res.data)
          let code = result.code
          if (code === "SUCCESS") {
            resolve(result)
          }
          reject(result.message)
        },
        fail(e) {
          reject(e.errMsg)
        }
      })
    })
  }

  static post(url: string, data?: any) {
    return this.request(url, data, "POST")
  }

  static get(url: string, data?: any) {
    return this.request(url, data, "GET")
  }

  static put(url: string, data?: any) {
    return this.request(url, data, "PUT")
  }

  static delete(url: string, data?: any) {
    return this.request(url, data, "DELETE")
  }
}

